<%@page import="org.openid4java.consumer.NonceVerifier"%>
<%@ page session="true" %>
<%@ page import="org.openid4java.discovery.Identifier,org.openid4java.discovery.DiscoveryInformation,org.openid4java.message.ax.FetchRequest,org.openid4java.message.ax.FetchResponse,org.openid4java.message.ax.AxMessage,org.openid4java.message.*,org.openid4java.OpenIDException,java.util.List,java.io.IOException,javax.servlet.http.HttpSession,javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse,org.openid4java.consumer.ConsumerManager,org.openid4java.consumer.InMemoryConsumerAssociationStore,org.openid4java.consumer.VerificationResult" %>
<%@ page import="org.openid4java.consumer.*" %>
<%@ page import="net.sf.ehcache.*" %>
<%@ page import="org.openid4java.consumer.*" %>
<%@ page import="org.openid4java.message.sreg.*" %>

<%
			ConsumerManager manager = (ConsumerManager) pageContext
			.getAttribute("consumermanager",
			PageContext.APPLICATION_SCOPE);
	if (manager == null) {
		ConsumerManager newmgr = new ConsumerManager();
		newmgr.setAssociations(new InMemoryConsumerAssociationStore());
		newmgr.setNonceVerifier(new InMemoryNonceVerifier(5000));
		pageContext.setAttribute("consumermanager", newmgr,
		PageContext.APPLICATION_SCOPE);
		manager = (ConsumerManager) pageContext.getAttribute(
		"consumermanager", PageContext.APPLICATION_SCOPE);

		// this is run in clustering mode, we need to set the cache
		//RegistryEhCache mycache = new RegistryEhCache();
		//NonceVerifier myverif = mycache.getNonceVerifier();
		

	}

	try {
		// --- processing the authentication response

		// extract the parameters from the authentication response
		// (which comes in as a HTTP request from the OpenID provider)
		ParameterList responselist = new ParameterList(request
		.getParameterMap());

		// retrieve the previously stored discovery information
		DiscoveryInformation discovered = (DiscoveryInformation) session	.getAttribute("openid-disco");

		if (discovered == null) {
			System.out.println("the DiscoveryInformation was not found in the session");
		}

		// extract the receiving URL from the HTTP request
		StringBuffer receivingURL = request.getRequestURL();
		String queryString = request.getQueryString();

		if (queryString != null && queryString.length() > 0)
			receivingURL.append("?").append(request.getQueryString());

		System.out.println("reveivingURL: " + receivingURL.toString());
		System.out.println(session.getAttribute("openid-disco"));
		System.out.println("request params:" + responselist);

		NonceVerifier myverif = manager.getNonceVerifier();

	

		// verify the response; ConsumerManager needs to be the same
		// (static) instance used to place the authentication request
		VerificationResult verification = manager.verify(receivingURL
		.toString(), responselist, discovered);

		// examine the verification result and extract the verified identifier
		Identifier verified = verification.getVerifiedId();
		
		if (verified != null) {
			// success !

			AuthSuccess authSuccess = (AuthSuccess) verification
			.getAuthResponse();

	          //String email =  authSuccess.getParameterValue("openid.sreg.email"); 
	          //if ( email != null ) {
	        //	  session.setAttribute("openid-email",email);
	          //}
	          if (authSuccess.hasExtension(SRegMessage.OPENID_NS_SREG))
	          {
	              MessageExtension ext = authSuccess.getExtension(SRegMessage.OPENID_NS_SREG);

	              if (ext instanceof SRegResponse)
	              {
	                  SRegResponse sregResp = (SRegResponse) ext;
	                  
		              //    String fullName = sregResp.getAttributeValue("fullname");
	                  //String nickName = sregResp.getAttributeValue("nickname");
	                  String email = sregResp.getAttributeValue("email");
	                  if ( email != null ) 
	          	        session.setAttribute("openid-email",email);
	              }
	          }
	          
			
			String openid = authSuccess.getIdentity();
			//System.out.println(discovered.getClaimedIdentifier());
			// original line is:
			//session.setAttribute("openid", openid);
			// but I think it should be:
			String claimed = discovered.getClaimedIdentifier()
			.toString();
			if (claimed == null)
				claimed = openid;
			session.setAttribute("openid", claimed);

			// authSuccess.getClaimed() gives null for me...
			session.setAttribute("openid-claimed", authSuccess.getClaimed());

			//System.out.println("openid " +openid);
			//System.out.println("openid-claimed "+ session.getAttribute("openid-claimed"));

			

			response.sendRedirect("index.jsp");
			

		} else {
			session.setAttribute("message", "Failed Verification");
			String u = "login.jsp";
			response.sendRedirect(u);
			return;
		}
	} catch (OpenIDException e) {
		session.setAttribute("message", "Login Error! "
		+ e.getMessage());
		String u = "login.jsp";
		response.sendRedirect(u);
		return;

	}
%>